package ru.agiledev.akb.server.hibernate;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by a.kirillov
 * Date: 3/29/11 Time: 11:32 PM
 */
public class HibernateUtil {
    private static SessionFactory sessionFactory = null;
     static Logger logger = LoggerFactory.getLogger(HibernateUtil.class);
     private static SessionFactory buildSessionFactory() {
         try {
             // Create the SessionFactory from hibernate.cfg.xml
             //Set configuration from config file
             Configuration cfg = new Configuration().configure();

             cfg.setProperty("hibernate.connection.url","jdbc:mysql://80.77.85.46/dao_se");
			 cfg.setProperty("hibernate.connection.username", "akbApp");
			 cfg.setProperty("hibernate.connection.password", "akb_7ru57n01");

             logger.info(cfg+" build.");
             logger.info(cfg.getProperties().keys().toString());

             SessionFactory factory = cfg.buildSessionFactory();
             logger.info(factory + " created");

             return factory;
         }
         catch (Throwable ex) {
             logger.trace("Initial SessionFactory creation failed." + ex, ex);
             throw new ExceptionInInitializerError(ex);
         }
     }

     public static SessionFactory getSessionFactory() {
         if(sessionFactory==null){
             sessionFactory = buildSessionFactory();
         }
         return sessionFactory;
     }

     public static void shutdown() {
         // Close caches and connection pools
         getSessionFactory().close();
         sessionFactory = null;
     }

    public static Object getObjectById(Class type, Integer id, Session session) {
        Criteria criteria = session.createCriteria(type).add(Restrictions.idEq(id)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        List res = criteria.list();

        if (res.size() == 0 ||
                res.size() > 1 ||
                !type.isInstance(res.get(0))) {
            return null;
        }
        return res.get(0);
    }
}
